<template>
  <div>
    <div class="md:flex">
      <div class="enter-y md:w-1/2">
        <SiteAnalysis class="enter-y mt-2" :phone="phone" />
        <div class="mt-2">
          <NowInfo class="w-full" :phone="phone" />
          <Report class="w-full mt-2" :peopleInfo="userInfo" />
          <MyReserve class="w-full mt-2" />
        </div>
      </div>
      <div class="enter-y md:w-1/2">
        <!-- 右上角基本信息 -->
        <BasicInfo
          class="w-full !md:mx-4 !md:my-0 h-2/8"
          :checkDetailedInfo="checkDetailedInfo"
          :check3DInfo="check3DInfo"
          :phone="phone"
          :userId="userId"
        />
        <!-- 诊断建议 -->
        <HealthEvent_1 class="w-full !my-4 !md:mx-4 md:h-3/7" :phone="phone" />
      </div>
    </div>
  </div>
  <!-- 档案信息 弹窗 -->
  <div class="popup" v-show="isDetailedInfoVisible">
    <div class="popup-inner">
      <button className="popup-close-button" @click="() => (isDetailedInfoVisible = false)"
        ><CloseOutlined
      /></button>
      <div class="flex flex-row h-full">
        <div class="flex-none w-90 h-full p-4">
          <div class="h-full flex justify-between flex-col">
            <div>
              <Avatar :size="{ md: 45 }" style="height: 45px; width: 45px">
                <template #icon>
                  <img src="/resource/img/123.jpg" />
                </template>
              </Avatar>
              <div class="flex">
                <div class="flex">
                  <div class="mr-2 item_title">性别</div>
                  <div class="mr-2 content-title">{{ userInfo.sex }}</div>
                </div>
                <div class="flex">
                  <div class="mr-2 item_title">年龄</div>
                  <div class="mr-2 content-title">{{ userInfo.age || '---' }}</div>
                </div>
              </div>
              <div class="hr-style"></div>
              <div class="second-line flex md:mt-2">
                <div class="flex">
                  <div class="mr-2 item_title">身高</div>
                  <div class="mr-2 content-title">{{ userInfo.height || '---' }}cm</div>
                </div>
                <div class="flex">
                  <div class="mr-2 item_title">体重</div>
                  <div class="mr-2 content-title">{{ userInfo.weight || '---' }}kg</div>
                </div>
                <div class="flex">
                  <div class="mr-2 item_title">BMI</div>
                  <div class="mr-2 content-title">{{ bmidata }}</div>
                </div>
              </div>
              <div class="hr-style"></div>
              <div class="flex md:mt-2">
                <div class="item_title">病症</div>
                <div class="ml-2 mr-2 content-title">{{ userInfo.illness || '---' }}</div>
              </div>
            </div>
            <Divider />
            <div>
              <div id="wordcloud"></div>
              <div v-if="showModal" class="modal">
                <div class="modal-content">
                  <input v-model="newItem" placeholder="输入词云内容" />
                  <button class="button-1" @click="submitItem">{{
                    isEditMode ? '修改' : '添加'
                  }}</button>
                  <button class="button-1" @click="cancelEdit">取消</button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <Divider type="vertical" style="height: 100%" />
        <div class="flex-auto p-3 h-full">
          <Tabs v-model:activeKey="tabKey">
            <!-- 优化后的基础档案标签页 -->
            <TabPane key="1" tab="基础档案" class="h-full">
              <div class="basic-info-container">
                <!-- 个人基本信息卡片 -->
                <Card class="basic-info-card">
                  <div class="card-title">个人基本信息</div>
                  <div class="info-grid">
                    <div class="info-item">
                      <span class="info-label">姓名</span>
                      <span class="info-value">{{ userInfo.patientName || '---' }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">性别</span>
                      <span class="info-value">{{ userInfo.sex || '---' }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">年龄</span>
                      <span class="info-value">{{ userInfo.age || '---' }}岁</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">身份证号</span>
                      <span class="info-value">{{ userInfo.identificationNumber || '---' }}</span>
                    </div>
                    <!-- <div class="info-item">
                      <span class="info-label">民族</span>
                      <span class="info-value">{{ userInfo.ethnic || '---' }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">婚姻状态</span>
                      <span class="info-value">{{ userInfo.maritalStatus || '---' }}</span>
                    </div> -->
                  </div>
                </Card>

                <!-- 身体特征卡片 -->
                <Card class="basic-info-card mt-4">
                  <div class="card-title">身体特征</div>
                  <div class="info-grid">
                    <div class="info-item">
                      <span class="info-label">身高</span>
                      <span class="info-value">{{ userInfo.height || '---' }}cm</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">体重</span>
                      <span class="info-value">{{ userInfo.weight || '---' }}kg</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">BMI</span>
                      <span class="info-value">
                        {{ bmidata }}
                        <span v-if="bmidata !== '---'" :class="getBmiClass(bmidata)">{{
                          getBmiStatus(bmidata)
                        }}</span>
                      </span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">病症</span>
                      <span class="info-value">{{ userInfo.illness || '---' }}</span>
                    </div>
                  </div>
                </Card>

                <!-- 居住信息卡片 -->
                <Card class="basic-info-card mt-4">
                  <div class="card-title">居住信息</div>
                  <div class="info-grid">
                    <div class="info-item full-width">
                      <span class="info-label">地址</span>
                      <span class="info-value">{{ userInfo.address || '---' }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">居住地区</span>
                      <span class="info-value">{{ userInfo.residentialArea || '---' }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">籍贯</span>
                      <span class="info-value">{{ userInfo.origin || '---' }}</span>
                    </div>
                  </div>
                </Card>
              </div>
            </TabPane>

            <TabPane key="2" tab="就医记录" force-render>
              <Table :dataSource="dsMedicalRecord" :columns="columnsMedicalRecord" />
            </TabPane>
            <TabPane key="3" tab="日常体征">
              <Table :dataSource="dsDailySign" :columns="columnsDailySign" />
            </TabPane>
            <TabPane key="4" tab="养老服务">
              <Table
                :dataSource="dsOlderCaringService"
                :columns="columnsOlderCaringService"
                :pagination="{ pageSize: 9 }"
              />
            </TabPane>
            <TabPane key="5" tab="健康分析">
              <Table :dataSource="dsHealthAdvise" :columns="columnsHealthAdvise" />
            </TabPane>
          </Tabs>
          <!-- 仅在健康分析标签页显示获取分析按钮 -->
          <div v-if="tabKey === '5'" style="margin-top: 16px; text-align: right">
            <Button type="primary" @click="openUpdateModal">获取分析</Button>
          </div>

          <!-- 更新弹窗 -->
          <div v-if="showUpdateModal" class="modal_1">
            <div class="modal-content_1" style="text-align: center">
              <Icon icon="ant-design:exclamation-circle-outlined" class="ml-2" />
              <span style="margin-left: 8px">您将授权我们获取以下平台的数据</span>
              <div
                style="display: flex; align-items: center; justify-content: center; margin: 16px 0"
              >
                <span style="font-size: 18px; margin-right: 16px">请选择平台：</span>
                <select
                  v-model="selectedPlatform"
                  style="width: 320px; font-size: 16px; margin-right: 16px"
                >
                  <option value="zhongyang">众阳</option>
                  <option value="yileju">颐乐居</option>
                  <option value="hayida">哈医大</option>
                </select>
                <button class="button-1" @click="handleConfirmClick" :disabled="isConfirming"
                  >拉取</button
                >
              </div>
              <textarea
                v-model="pulledDataText"
                readonly
                rows="6"
                style="width: 90%; margin-top: 16px; resize: vertical"
                placeholder="结果将在此显示"
              ></textarea>
              <button class="button-1" @click="showUpdateModal = false">确定</button>
            </div>
          </div>

          <div v-if="showInfoModal" class="modal_1">
            <div class="modal-content_1" style="text-align: center">
              <spin v-if="loading" size="large" tip="加载中..." />
              <Icon icon="ant-design:exclamation-circle-outlined" class="ml-2" />
              <span style="margin-left: 8px">您将授权我们获取以下平台的数据</span>
              <div
                style="display: flex; align-items: center; justify-content: center; margin: 16px 0"
              >
                <span style="font-size: 18px; margin-right: 16px">请选择平台：</span>
                <select
                  v-model="selectedPlatform"
                  style="width: 320px; font-size: 16px; margin-right: 16px"
                >
                  <option value="zhongyang">众阳</option>
                  <option value="yileju">颐乐居</option>
                  <option value="hayida">哈医大</option>
                </select>
                <button class="button-1" @click="handleConfirmClick" :disabled="isConfirming"
                  >拉取</button
                >
              </div>
              <textarea
                v-model="pulledDataText"
                readonly
                rows="6"
                style="width: 90%; margin-top: 16px; resize: vertical"
                placeholder="结果将在此显示"
              ></textarea>
              <button class="button-1" @click="showInfoModal = false">确定</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 3D信息框 -->
  <div class="popup_3d" v-show="is3DInfoVisible">
    <div class="popup-inner_3d">
      <button className="popup-close-button_3d" @click="() => (is3DInfoVisible = false)"
        ><CloseOutlined
      /></button>
      <div class="flex flex-col h-full">
        <div
          class="flex-1 flex justify-center items-center bg-cover bg-center"
          style="background-image: url('/resource/health/img/detail/tou.png')"
        >
          <p class="text-white text-2xl font-bold">患者信息</p>
        </div>
        <HealthStatus :userInfo="userInfo" :phone="phone" />
      </div>
    </div>
  </div>

  <!-- 全屏加载蒙层 -->
  <div v-if="showLoading" class="loading-overlay">
    <div class="loading-content">
      <Spin size="large" tip="正在获取数据，请稍后..." />
    </div>
  </div>
</template>

<script lang="ts" setup name="Analysis">
  import NowInfo from './components/NowInfo.vue';
  import Report from './components/Report2.vue';
  import Search from './components/Search.vue';
  import MyReserve from './components/MyReserve.vue';
  import GrowCard from './components/GrowCard.vue';
  import SiteAnalysis from './components/SiteAnalysis.vue';
  import VisitSource from './components/VisitSource.vue';
  import VisitRadar from './components/VisitRadar.vue';
  import SalesProductPie from './components/SalesProductPie.vue';
  import BasicInfo from './components/BasicInfo.vue';
  import HealthEvent_1 from './components/HealthEvent_1.vue';
  import MedicalInsurance from './components/MedicalInsurance.vue';
  import { ref, onMounted, computed } from 'vue';
  import { getBaseInfo, getMappingId } from '/@/api/sys/desktopApi';
  import { labelUpdate, insertAdvices } from '/@/api/sys/user';
  import { useUserStore } from '/@/store/modules/user';
  import { CollapseTransition } from '/@/components/Transition';
  import { CloseOutlined } from '@ant-design/icons-vue';
  import { Card, Divider, Tabs, TabPane, Avatar, Button, Table, Spin } from 'ant-design-vue';
  // import * as d3 from 'd3';
  // import * as cloud from 'd3-cloud';
  import * as d3 from 'd3'; // 保留 d3 的命名导入（正确）
  import cloud from 'd3-cloud'; // 将 d3-cloud 改为默认导入（关键修正）
  import HealthStatus from './components/HealthStatus.vue';
  import { Icon } from '/@/components/Icon';
  import axios from 'axios';
  import { common } from '@fullcalendar/core/internal-common';
  import { dailySignsListData } from '/@/api/information/dailySigns';
  import { historyOrdersListData } from '/@/api/information/historyOrders';
  import { listAdvice } from '/@/api/sys/desktopApi';

  const userStore = useUserStore();
  const showUpdateModal = ref(false);
  const showInfoModal = ref(false);
  const isConfirming = ref(false);
  const showLoading = ref(false);
  let selectedPlatform = ref('yileju');

  const userInfo = ref({});
  const phone = userStore.getUserInfo.loginCode;
  const userId = userStore.getUserInfo.userCode;

  const words = ref([]);
  const showModal = ref(false);
  const newItem = ref('');
  const isEditMode = ref(false);
  const mappingId = ref({});
  const currentEditIndex = ref(0);

  // 数据源定义
  const dsMedicalRecord = ref([]); // 就医记录
  const dsDailySign = ref([]); // 日常体征
  const dsPhysicalExamination = ref([]);
  const dsOlderCaringService = ref([]); // 养老服务
  const dsServiceRecommendation = [];
  const dsHealthAdvise = ref([]);
  const dsHealthEvaluation = [];

  // 获取当前时间（YYYY-MM-DD）
  const getCurrentTime = () => {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  // 格式化身份证号（中间8位隐藏）
  const formatIdCard = (id: string) => {
    if (!id) return '';
    return id.replace(/(\d{6})(\d{8})(\d{4})/, '$1********$3');
  };

  // 根据BMI值判断状态
  const getBmiStatus = (bmi: string) => {
    const bmiValue = parseFloat(bmi);
    if (bmiValue < 18.5) return '偏瘦';
    if (bmiValue < 24) return '正常';
    if (bmiValue < 28) return '超重';
    return '肥胖';
  };

  // 根据BMI状态获取样式类
  const getBmiClass = (bmi: string) => {
    const status = getBmiStatus(bmi);
    switch (status) {
      case '偏瘦':
        return 'bmi-tag lean';
      case '正常':
        return 'bmi-tag normal';
      case '超重':
        return 'bmi-tag overweight';
      case '肥胖':
        return 'bmi-tag obese';
      default:
        return '';
    }
  };

  onMounted(async () => {
    try {
      console.log(123);
      // 获取基础信息
      const data = await getBaseInfo({ phone: userId });
      userInfo.value = data;
      console.log(123);

      console.log('用户ID', userId);
      console.log('用户信息', userInfo.value);

      // 词云数据处理（去重）
      if (data.biaoQian) {
        const uniqueTags = [...new Set(userInfo.value.biaoQian.split('|'))];
        const validTags = uniqueTags.filter((tag) => tag.trim() !== '');
        words.value = validTags.map((item) => ({ text: item, size: 24 }));
        generateWordCloud(words.value);
      }

      // 获取映射ID
      mappingId.value = await getMappingId({ phone: userId });

      // 处理历史订单数据
      const orderParams = { phone: phone };
      const orderRes = await historyOrdersListData(orderParams);
      const allOrders = orderRes.list || [];

      // 1. 就医记录：筛选含"医院"的机构
      dsMedicalRecord.value = allOrders
        .filter((item) => item.shopName?.includes('医院'))
        .map((item) => ({
          key: item.shopId,
          time: item.paymentTime || item.createTime,
          serviceName: item.productName,
          serviceType: item.classifyName,
          agency: item.shopName,
          source: item.sourcePlatform,
        }));

      // 2. 养老服务：筛选不含"医院"的机构
      dsOlderCaringService.value = allOrders
        .filter((item) => !item.shopName?.includes('医院'))
        .map((item) => ({
          key: item.shopId,
          time: item.paymentTime || item.createTime,
          serviceName: item.productName,
          serviceType: item.classifyName,
          agency: item.shopName,
          source: item.sourcePlatform,
        }));

      // 3. 日常体征数据
      const signParams = { phone: phone };
      const signRes = await dailySignsListData(signParams);
      const signList = signRes.list || [];
      dsDailySign.value = signList.map((item) => ({
        key: item.tid,
        time: item.createTime,
        heartRate: item.heartRate || '---',
        breathe: item.breathe || '---',
        diastolicPressure: item.diastolicPressure || '---',
        systolicPressure: item.systolicPressure || '---',
        temperature: item.temperature || '---',
      }));

      // 4. 体检记录
      dsPhysicalExamination.value = await dailySignsListData({
        phone: phone,
        type: 'physicalExamination',
        pageSize: 100,
      }).then((res) => res.list || []);

      // 5. 健康分析数据（去重）
      const timeNow = getCurrentTime();
      const adviceRes = await listAdvice({ phone: phone, adate: timeNow });
      const adviceList = Array.isArray(adviceRes) ? adviceRes : adviceRes?.list ?? [];

      const uniqueMap = new Map();
      adviceList.forEach((item) => {
        const key = `${item.riqi || item.create_date?.split('T')[0] || ''}-${
          item.biaoti || '无标题'
        }`;
        if (!uniqueMap.has(key)) uniqueMap.set(key, item);
      });

      const uniqueAdviceList = Array.from(uniqueMap.values());
      dsHealthAdvise.value = uniqueAdviceList.map((item) => ({
        key: item.id || Date.now() + Math.random(),
        date: item.riqi || item.create_date?.split('T')[0] || '',
        title: item.biaoti || '无标题',
        description: item.miaoshu || '无描述',
      }));
    } catch (error) {
      console.error('数据加载失败:', error);
    }
  });

  // 平台映射关系
  const platformMap: Record<string, string> = {
    zhongyang: 'platformAId',
    yileju: 'platformBId',
    hayida: 'platformDId',
  };
  const platformTask: Record<string, string> = {
    zhongyang: 'summarize_zy_service_records',
    yileju: 'summarize_ylj_order_records',
    hayida: 'summarize_hyd_service_records',
  };
  const pulledDataText = ref('');
  const loading = ref(false);

  // 重新加载数据
  async function reloadData() {
    try {
      const data = await getBaseInfo({ phone: userId });
      userInfo.value = data;

      // 词云数据重新处理（去重）
      if (data.biaoQian) {
        const uniqueTags = [...new Set(data.biaoQian.split('|'))];
        const validTags = uniqueTags.filter((tag) => tag.trim() !== '');
        words.value = validTags.map((item) => ({ text: item, size: 24 }));
        generateWordCloud(words.value);
      }

      mappingId.value = await getMappingId({ phone: userId });
    } catch (error) {
      console.error('数据重载失败:', error);
    }
  }

  // 拉取数据处理
  async function handleConfirmClick() {
    isConfirming.value = true;
    showLoading.value = true;
    try {
      await handleConfirm();
    } finally {
      showLoading.value = false;
      isConfirming.value = false;
    }
  }

  async function handleConfirm() {
    loading.value = true;
    try {
      mappingId.value = await getMappingId({ phone: userId });
      const user_id = mappingId.value[platformMap[selectedPlatform.value]];
      const task_name = platformTask[selectedPlatform.value];
      console.log('映射ID:', mappingId.value);
      if (!user_id) {
        alert(`用户不zheg在该平台---${user_id}-${mappingId.value}`);
        return;
      }

      const res = await axios.post(
        `https://hgdzhyypt.msuncloud.cn:20145/main/execute-task`,
        { user_id: user_id, task_name: task_name },
        { timeout: 100000, headers: { 'Content-Type': 'application/json' } },
      );

      const report = res.data.data || '';
      const labels = report.label || '';
      const displaylabels = labels.split('|').length > 0 ? labels.split('|').join('、') : '无';
      const trend = report.trend || '';
      const basicinfo = report.basicinfo || '';

      const adviceList = [
        { phone: phone, biaoti: '基础分析', miaoshu: basicinfo },
        { phone: phone, biaoti: '趋势分析', miaoshu: trend },
      ];

      if (basicinfo && basicinfo !== '暂无服务记录') {
        // 标签去重
        // 1. 处理原有标签和新标签（避免null/undefined，转为空字符串）
        const oldLabels = (userInfo.value?.biaoQian || '').trim();
        const newLabels = labels.trim();

        // 2. 合并标签并分割成数组（按 | 分割，过滤空字符串）
        const allLabels = [...oldLabels.split('|'), ...newLabels.split('|')].filter(label => label);

        // 3. 去重（利用Set的唯一性）
        const uniqueLabels = [...new Set(allLabels)];

        // 4. 重新拼接为 | 分隔的字符串
        const finalLabels = uniqueLabels.join('|');

        await labelUpdate({
          patientPhone: userId,
          biaoQian: finalLabels
        });
        await insertAdvices(adviceList);
        pulledDataText.value = `【基础分析】\n${basicinfo}\n【趋势分析】\n${trend}\n【标签】\n${displaylabels}`;
        await reloadData();
      }
      else
      {
        pulledDataText.value = `暂无服务记录！`;
        await reloadData();
      }
    } catch (e) {
      console.error('拉取失败:', e);
    } finally {
      loading.value = false;
    }
  }

  // 打开弹窗方法
  async function openUpdateModal() {
    showUpdateModal.value = true;
  }
  async function openInfoModal() {
    showInfoModal.value = true;
  }

  // 词云生成
  function generateWordCloud(words) {
    d3.select('#wordcloud').html('');
    const layout = cloud()
      .size([360, 300])
      .words(words)
      .padding(5)
      .rotate(0)
      .font('Impact')
      .fontSize((d) => d.size)
      .on('end', draw);

    layout.start();

    function draw(words) {
      d3.select('#wordcloud')
        .append('svg')
        .attr('width', layout.size()[0])
        .attr('height', layout.size()[1])
        .append('g')
        .attr('transform', `translate(${layout.size()[0] / 2},${layout.size()[1] / 2})`)
        .selectAll('text')
        .data(words)
        .enter()
        .append('text')
        .style('font-size', (d) => `${d.size}px`)
        .style('font-family', 'Impact')
        .style('fill', (d, i) => d3.schemeCategory10[i % 10])
        .attr('text-anchor', 'middle')
        .attr('transform', (d) => `translate(${d.x},${d.y})rotate(${d.rotate})`)
        .text((d) => d.text);
    }
  }

  // 词云编辑方法
  const addItem = () => {
    newItem.value = '';
    isEditMode.value = false;
    showModal.value = true;
  };
  const editItem = () => {
    if (words.value.length === 0) {
      alert('没有可修改的词云内容！');
      return;
    }
    currentEditIndex.value = 0;
    newItem.value = words.value[currentEditIndex.value].text;
    isEditMode.value = true;
    showModal.value = true;
  };
  const submitItem = () => {
    if (isEditMode.value) {
      words.value[currentEditIndex.value].text = newItem.value;
    } else {
      words.value.push({ text: newItem.value, size: 24 });
    }
    generateWordCloud(words.value);
    showModal.value = false;
  };
  const cancelEdit = () => {
    showModal.value = false;
  };

  // 弹窗控制
  let isDetailedInfoVisible = ref(false);
  const checkDetailedInfo = () => {
    isDetailedInfoVisible.value = true;
  };
  let is3DInfoVisible = ref(false);
  const check3DInfo = () => {
    is3DInfoVisible.value = true;
  };
  let tabKey = ref('1');

  // BMI计算
  const bmidata = computed(() => {
    if (userInfo.value && userInfo.value.height && userInfo.value.weight) {
      const heightInMeters = userInfo.value.height / 100;
      const bmi = userInfo.value.weight / (heightInMeters * heightInMeters);
      return bmi.toFixed(2);
    }
    return '---';
  });

  // 表格列定义 - 就医记录
  const columnsMedicalRecord = [
    { title: '时间', dataIndex: 'time', key: 'time' },
    { title: '服务名', dataIndex: 'serviceName', key: 'serviceName' },
    { title: '服务类别', dataIndex: 'serviceType', key: 'serviceType' },
    { title: '机构', dataIndex: 'agency', key: 'agency' },
    { title: '来源平台', dataIndex: 'source', key: 'source' },
  ];

  // 表格列定义 - 日常体征
  const columnsDailySign = [
    { title: '时间', dataIndex: 'time', key: 'time' },
    { title: '心率(次/分)', dataIndex: 'heartRate', key: 'heartRate' },
    { title: '呼吸(次/分)', dataIndex: 'breathe', key: 'breathe' },
    { title: '收缩压(mmhg)', dataIndex: 'systolicPressure', key: 'systolicPressure' },
    { title: '舒张压(mmhg)', dataIndex: 'diastolicPressure', key: 'diastolicPressure' },
    { title: '体温(℃)', dataIndex: 'temperature', key: 'temperature' },
  ];

  // 表格列定义 - 养老服务
  const columnsOlderCaringService = [
    { title: '时间', dataIndex: 'time', key: 'time' },
    { title: '服务名', dataIndex: 'serviceName', key: 'serviceName' },
    { title: '服务类别', dataIndex: 'serviceType', key: 'serviceType' },
    { title: '机构', dataIndex: 'agency', key: 'agency' },
    { title: '来源平台', dataIndex: 'source', key: 'source' },
  ];

  // 表格列定义 - 健康分析
  const columnsHealthAdvise = [
    { title: '日期', dataIndex: 'date', key: 'date', width: 120 },
    { title: '标题', dataIndex: 'title', key: 'title', width: 180 },
    { title: '描述', dataIndex: 'description', key: 'description', ellipsis: true, width: 'auto' },
  ];

  // 其他表格列定义
  const columnsPhysicalExamination = [
    { title: '体检日期', dataIndex: 'name', key: 'name' },
    { title: '体检医院', dataIndex: 'name', key: 'name' },
    { title: '体检项目', dataIndex: 'name', key: 'name' },
    { title: '体检照片', dataIndex: 'name', key: 'name' },
    { title: '数据来源', dataIndex: 'name', key: 'name' },
  ];
  const columnsServiceRecommendations = [
    { title: '服务', dataIndex: 'name', key: 'name' },
    { title: '服务商', dataIndex: 'name', key: 'name' },
    { title: '规格', dataIndex: 'name', key: 'name' },
    { title: '服务简介', dataIndex: 'name', key: 'name' },
    { title: '推荐理由', dataIndex: 'name', key: 'name' },
  ];
  const columnsHealthEvaluation = [
    { title: '日期', dataIndex: 'name', key: 'name' },
    { title: '图标', dataIndex: 'name', key: 'name' },
    { title: '标题', dataIndex: 'name', key: 'name' },
    { title: '描述', dataIndex: 'name', key: 'name' },
  ];
</script>

<style>
  /* 基础档案优化样式 */
  .basic-info-container {
    padding: 20px;
    max-width: 900px;
    margin: 0 auto;
  }
  .basic-info-card {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    border: 1px solid #f0f0f0;
    overflow: hidden;
  }
  .card-title {
    font-size: 16px;
    font-weight: 600;
    color: #1f2329;
    padding: 12px 20px;
    border-bottom: 1px solid #f0f0f0;
    background-color: #fafafa;
  }
  .info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 16px;
    padding: 20px;
  }
  .info-item {
    display: flex;
    flex-direction: column;
  }
  .info-item.full-width {
    grid-column: 1 / -1;
  }
  .info-label {
    font-size: 13px;
    color: #6b7280;
    margin-bottom: 4px;
    line-height: 1.5;
  }
  .info-value {
    font-size: 14px;
    color: #111827;
    line-height: 1.5;
    word-break: break-all;
  }
  .bmi-tag {
    display: inline-block;
    padding: 0 6px;
    margin-left: 8px;
    border-radius: 4px;
    font-size: 12px;
    color: white;
  }
  .bmi-tag.lean {
    background-color: #4096ff;
  }
  .bmi-tag.normal {
    background-color: #52c41a;
  }
  .bmi-tag.overweight {
    background-color: #faad14;
  }
  .bmi-tag.obese {
    background-color: #f5222d;
  }
  @media (max-width: 768px) {
    .info-grid {
      grid-template-columns: 1fr;
    }
    .basic-info-container {
      padding: 10px;
    }
  }

  /* 原有样式保持不变 */
  .loading-spinner {
    border: 6px solid #f3f3f3;
    border-top: 6px solid #1677ff;
    border-radius: 50%;
    width: 48px;
    height: 48px;
    animation: spin 1s linear infinite;
    margin: 0 auto;
  }
  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
  .ant-table-thead > tr > th {
    text-align: center !important;
    font-weight: 600;
    font-size: 16px;
    background: #f7f8fa;
  }
  .ant-table-tbody > tr > td {
    text-align: center !important;
    font-size: 14px;
  }
  .ant-table-tbody > tr:nth-child(even) > td {
    background: #fafbfc;
  }
  .ant-table-tbody > tr:nth-child(odd) > td {
    background: #fff;
  }

  .modal_1 {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.35);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 10000;
  }
  .modal-content_1 {
    background: #fff;
    padding: 36px 48px 32px 48px;
    border-radius: 16px;
    min-width: 480px;
    min-height: 420px;
    max-width: 90vw;
    max-height: 80vh;
    box-shadow: 0 12px 36px rgba(0, 0, 0, 0.18);
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    overflow: auto;
    font-family: 'Microsoft YaHei', Arial, sans-serif;
  }
  .modal-content_1 > span {
    font-size: 18px;
    font-weight: 500;
    margin-bottom: 12px;
    display: block;
  }

  .loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
  }
  .loading-content {
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    text-align: center;
  }
  .modal-content_1 .ant-select,
  .modal-content_1 .ant-select-selector {
    height: 48px !important;
    font-size: 24px !important;
    display: flex;
    align-items: center;
  }
  .modal-content_1 .ant-select-selector {
    padding: 0 16px !important;
    border: 2px solid #000 !important;
    border-radius: 10px !important;
    box-shadow: none !important;
    background: #fff !important;
  }
  .modal-content_1 button.button-1 {
    height: 30px;
    line-height: 48px;
    padding: 0 32px;
    margin: 0;
    font-size: 12px;
    border-radius: 10px;
    border: none;
    background: linear-gradient(90deg, #1677ff 60%, #50aaff 100%);
    color: #fff;
    cursor: pointer;
    font-weight: 500;
    letter-spacing: 1px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .modal-content_1 button.button-1:hover {
    background: linear-gradient(90deg, #409eff 60%, #1677ff 100%);
  }
  .modal-content_1 textarea {
    width: 95%;
    margin: 10px 0 0 0;
    margin-bottom: 10px;
    padding: 12px;
    border-radius: 6px;
    border: 1px solid #e4e7ed;
    font-size: 15px;
    color: #333;
    background: #fafbfc;
    resize: vertical;
    min-height: 120px;
    max-height: 260px;
    box-sizing: border-box;
  }

  .popup {
    z-index: 9999;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgba(203, 202, 202, 0.7);
  }
  .popup > * {
    border-radius: 4px;
  }
  .popup-inner {
    position: relative;
    width: 90%;
    height: 90%;
    overflow-y: auto;
    border: 1px solid #006699;
    padding-top: 8px;
    padding-bottom: 8px;
    padding-left: 8px;
    padding-right: 28px;
    background-color: #ffffff;
  }
  .popup-inner > .popup-close-button {
    box-sizing: content-box;
    position: absolute;
    right: 2px;
    top: 2px;
    padding-bottom: 1px;
    padding-left: 7px;
    padding-right: 7px;
    border-width: 1px;
    border-style: outset;
    border-color: buttonborder;
    border-image: initial;
    margin: 0;
    opacity: 60%;
    border-radius: 4px;
  }
  .popup-inner > .popup-close-button:hover {
    opacity: 100%;
  }

  .module_title {
    color: #009688;
    font-size: 22px;
  }
  .module_title .btn {
    font-size: 18px;
    color: #557bfa;
    cursor: pointer;
  }
  .hr-style {
    border-top: 1px solid #4caf50;
  }
  .item_title {
    font-size: 14px;
    margin-top: 15px;
    color: #000000;
  }
  .content-title {
    color: #009688;
    font-size: 18px;
    margin-top: 5px;
    margin-right: 20px;
  }

  .popup_3d {
    z-index: 9999;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgba(203, 202, 202, 0.7);
  }
  .popup-inner_3d {
    position: relative;
    width: 90%;
    height: 90%;
    overflow-y: auto;
    border: 1px solid #006699;
    padding-top: 8px;
    padding-bottom: 8px;
    padding-left: 8px;
    padding-right: 28px;
    background-color: #ffffff;
    background-image: url('/resource/health/img/detail/详情-背景图.png');
    background-size: cover;
    background-position: center;
  }
  .popup-inner_3d > .popup-close-button_3d {
    box-sizing: content-box;
    position: absolute;
    right: 2px;
    top: 2px;
    padding-bottom: 1px;
    padding-left: 7px;
    padding-right: 7px;
    border-width: 1px;
    border-style: outset;
    border-color: buttonborder;
    border-image: initial;
    margin: 0;
    opacity: 60%;
    border-radius: 4px;
    background-image: url('/resource/health/img/关闭按钮.png');
    background-size: cover;
    background-position: center;
  }

  .modal {
    position: fixed;
    top: 40%;
    left: 5%;
    width: 25%;
    height: 15%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .modal-content {
    background-color: white;
    padding: 20px;
    border-radius: 5px;
  }
  input {
    padding: 10px;
    margin-right: 10px;
  }
  .button-1 {
    padding: 10px;
    margin-top: 10px;
  }
</style>
